package com.gao.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gao.domain.User;
import com.gao.service.UserService;
import com.gao.service.impl.UserServiceImpl;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("LoginServlet??doGet??????????...");
	}


	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//??????????
		String username = request.getParameter("username");
		System.out.println("jsp获得的username="+username);
		String password = request.getParameter("password");
		System.out.println("jsp获得的password="+password);

		//???????
		UserService userService= new UserServiceImpl();
		User user = null;
		try {
			user = userService.login(username, password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("获得的数据"+user);

		//?ж???????????????
		if(user!=null){
			//???????????????????浽session??
			HttpSession session = request.getSession();
			session.setAttribute("user", user);

			//??????1-????????
			//response.sendRedirect("index.jsp");
			response.sendRedirect("ProductsIndexServlet");
		}else{
			//??????
			request.setAttribute("msg", "用户名或者密码错误，请重新登录！");
			//response.sendRedirect("login.jsp");
			//??????2-???????
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
		
	}

}
